package cn.wen.core.http.callback;

import android.text.TextUtils;

import java.io.IOException;

import cn.wen.core.db.CacheUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * OKHttp的回调
 */

public class OkCallback implements Callback {
    private ICallback mCallback;
    private boolean mIsCache;
    private String mUrl;

    public OkCallback(String url, boolean isCache, ICallback callback) {
        mUrl = url;
        mIsCache = isCache;
        mCallback = callback;
        checkCache(mUrl, mIsCache, mCallback);
    }

    /**
     * 检查缓存
     */
    private void checkCache(String finalUrl, boolean isCache, ICallback callback) {
        if (isCache) {
            String cacheJson = CacheUtil.getCacheJson(finalUrl);
            if (!TextUtils.isEmpty(cacheJson)) {
                if (callback != null) {
                    callback.onSucceed(cacheJson);
                    callback.onAfter();
                }
            }
        }
    }

    @Override
    public void onFailure(Call call, IOException e) {
        if (mCallback != null) {
            mCallback.onError(e);
            mCallback.onAfter();
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String result = response.body().string();
        String cacheJson = CacheUtil.getCacheJson(mUrl);
        // 比较缓存，如果一样就不更新
        if (mIsCache && !TextUtils.isEmpty(cacheJson) && result.equals(cacheJson)) {
            mCallback.onAfter();
            return;
        }
        if (mCallback != null) {
            mCallback.onSucceed(result);
            mCallback.onAfter();
        }
        // 缓存数据
        CacheUtil.cacheJson(mUrl, result);
    }
}
